package me.flyray.admin.rest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.flyray.admin.biz.*;
import me.flyray.admin.entity.Element;
import me.flyray.admin.constant.AdminCommonConstant;
import me.flyray.admin.entity.Menu;
import me.flyray.admin.entity.ResourceAuthority;
import me.flyray.admin.entity.UserRole;
import me.flyray.common.context.BaseContextHandler;
import me.flyray.common.msg.BaseApiResponse;
import me.flyray.common.msg.TableResultResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import me.flyray.admin.vo.AuthorityMenuTree;
import me.flyray.admin.vo.MenuTree;
import me.flyray.auth.common.config.UserAuthConfig;
import me.flyray.auth.common.util.jwt.IJWTInfo;
import me.flyray.auth.common.util.jwt.JWTHelper;
import me.flyray.common.rest.BaseController;
import me.flyray.common.util.TreeUtil;

import tk.mybatis.mapper.entity.Example;

/**
 * ${DESCRIPTION}
 *
 * @author bolei
 * @create 2017-06-12 8:49
 */
@Controller
@RequestMapping("menu")
public class MenuController extends BaseController<MenuBiz, Menu> {

    @Autowired
    private ElementBiz elementBiz;
    @Autowired
    private UserBiz userBiz;


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public List<Menu> list(String title) {
        Example example = new Example(Menu.class);
        if (StringUtils.isNotBlank(title)) {
            example.createCriteria().andLike("title", "%" + title + "%");
        }
        return baseBiz.selectByExample(example);
    }

    @RequestMapping(value = "/detail/{id}",method = RequestMethod.GET)
    @ResponseBody
    public BaseApiResponse<Menu> getDetail(@PathVariable int id){
        Object o = baseBiz.selectById(id);
        return  BaseApiResponse.newSuccess((Menu)baseBiz.selectById(id));
    }

    @RequestMapping(value = "/delete/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public BaseApiResponse<Menu> delete(@PathVariable int id){
        baseBiz.deleteById(id);
        return BaseApiResponse.newSuccess();
    }

    /**
     * 查询菜单下的按钮
     * @param limit
     * @param offset
     * @param name
     * @param menuId
     * @return
     */
    @RequestMapping(value = "/element", method = RequestMethod.GET)
    @ResponseBody
    public TableResultResponse<Element> page(@RequestParam(defaultValue = "10") int limit,
                                             @RequestParam(defaultValue = "1") int offset, String name, @RequestParam(defaultValue = "0") int menuId) {
        Example example = new Example(Element.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("menuId", menuId);
        if(StringUtils.isNotBlank(name)){
            criteria.andLike("name", "%" + name + "%");
        }
        List<Element> elements = elementBiz.selectByExample(example);
        return new TableResultResponse<Element>(elements.size(), elements);
    }

    /**
     * 查询用户在该应用下的菜单
     * @param appId
     * @return
     */
    @RequestMapping(value = "/user/app/authorityTree", method = RequestMethod.GET)
    @ResponseBody
    public List<MenuTree> userAuthorityAppMenu(String appId){
        String userId = userBiz.getUserByUsername(getCurrentUserName()).getUserId();
        return getMenuTree(baseBiz.getAuthorityAppMenuByUserIdAppId(userId,appId),AdminCommonConstant.ROOT);
    }

    @RequestMapping(value = "/tree", method = RequestMethod.GET)
    @ResponseBody
    public List<MenuTree> listMenu(Integer parentId) {
        try {
            if (parentId == null) {
                parentId = AdminCommonConstant.ROOT;
            }
        } catch (Exception e) {
            return new ArrayList<MenuTree>();
        }
        Example example = new Example(Menu.class);
        Menu parent = baseBiz.selectById(parentId);
        example.createCriteria().andLike("path", parent.getPath() + "%").andNotEqualTo("id",parent.getId());
        return getMenuTree(baseBiz.selectByExample(example), parent.getId());
    }

    private List<MenuTree> getMenuTree(List<Menu> menus,int root) {
        List<MenuTree> trees = new ArrayList<MenuTree>();
        MenuTree node = null;
        for (Menu menu : menus) {
            node = new MenuTree();
            BeanUtils.copyProperties(menu, node);
            node.setLabel(menu.getTitle());
            node.setParentId(String.valueOf(menu.getParentId()));
            node.setId(String.valueOf(menu.getId()));
            trees.add(node);
        }
        return TreeUtil.bulid(trees,String.valueOf(root)) ;
    }




}
